import { createRouter, createWebHistory } from 'vue-router'
import layout from '../views/layout/index.vue'
import Cookies from "js-cookie"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: layout,
      redirect: "/dashboard",
      children: [
        {
          path: '/dashboard',
          component: () => import("../views/DashboardView.vue"),
          meta: { title: "首页" }
        },
      ]
    },
    {
      path: '/score',
      component: layout,
      redirect: '/score/index',
      meta: { title: '成绩管理' },
      children: [
        {
          path: '/index',
          component: () => import("../views/examPaperAnswer/index.vue"),
          meta: { title: '答卷列表' }
        },
      ]
    },
          {
      path: '/notice',
      component: layout,
      redirect: "/notice/list",
      meta: { title: "消息中心" },
      children: [
        {
          path: '/list',
          component: () => import("../views/message/item.vue"),
          meta: { title: "消息列表" },
        },
        {
          path: '/send',
          component: () => import("../views/notice/send.vue"),
          meta: { title: "消息发送" },
        },
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import("../views/LoginView.vue"),
      meta: {
        hidden: true
      }
    },
  ],
})

// 路由守卫
router.beforeEach((to, form, next) => {
  // 1，是否登录
  const token = Cookies.get("JSESSIONID")
  if (token) {
    if (to.path == "/login") {
      next("/")
    } else {
      next()
    }
  } else {
    if (to.path == "/login") {
      // 如果去的是Login 就放行
      next()
    } else {
      // 如果去的不是login，就去登录页面
      next("/login")
    }
  }
})


export default router
